import logging
from rest_framework import viewsets
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.contrib import auth
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from django.contrib.auth.models import update_last_login
from users_manage.redis_token import Token
from users_manage import serializers

logger = logging.getLogger("default")


class UsersManage(viewsets.GenericViewSet):

    # 注册: 用户名、邮箱可以为Null、密码1、确认密码2; 不做token权限验证
    @action(methods=['post'], detail=False, permission_classes=())
    def register(self, request):
        serializer = serializers.RegisterDeserializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        validated_data = serializer.validated_data
        username = validated_data['username']
        email = validated_data['email']
        password1 = validated_data['password']
        password2 = validated_data['password2']
        if User.objects.filter(username=username):
            return Response({'msg': '该用户已注册！', 'code': 400})
        else:
            if password1 == password2:
                user_data = {'username': username, 'password': make_password(password1)}
                if email:  # User.object.create中，如果传有email字段，则email不能为空。
                    user_data.update({'email': email})
                user_serializer = serializers.RegisterSerializer(data=user_data)
                if user_serializer.is_valid():
                    user_serializer.save()
                    return Response({'msg': '注册成功！', 'code': 200})
                else:
                    return Response({'msg': user_serializer.errors, 'code': 400})
            else:
                return Response({'msg': '两次密码不一致！', 'code': 400})

    # 登录：用户名/密码验证，不做token权限验证 2024-08-29 13:22:47.052224
    @action(methods=['post'], detail=False, permission_classes=())
    def login(self, request):
        serializer = serializers.LoginDeserializers(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        validated_data = serializer.validated_data
        _username = validated_data['username']
        _password = validated_data['password']
        # TODO 邮箱登录、手机登录
        user = auth.authenticate(username=_username, password=_password)

        if user is not None:
            auth.login(request, user)
            token = Token.create_token(user)  # TODO 生成token
            update_last_login(None, user)
            user_data = {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'token': token
            }
            print(user_data)
            serializer = serializers.LoginSerializer(user_data)
            return Response(serializer.data)
        else:
            return Response({'msg': 'Invalid credentials', 'code': 400})

    # 登出：账户名
    @action(methods=['post'], detail=False, permission_classes=())
    def logout(self, request):
        token_key = request.META.get('HTTP_TOKEN')
        logger.info("logout token = {}".format(token_key))
        Token.remove_token(token_key)
        auth.logout(request)
        return Response({'msg': '登出成功！', 'code': 200})
